package com.example.serverclient.demo.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Aspect
@Component
public class LoginAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginAspect.class);

    @Pointcut("@annotation(com.example.serverclient.demo.aop.CheckToken)")
    public void annotationPointcut() {
    }

    @Around("annotationPointcut() && @annotation(checkToken)")
    public Object around(ProceedingJoinPoint pjp, CheckToken checkToken) throws Throwable {
        // 获取请求方法
        Signature sig = pjp.getSignature();
        String method = pjp.getTarget().getClass().getName() + "." + sig.getName();

        // 获取请求的头部的token
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();
        String header = request.getHeader("token");
        if (null == header || "".equals(header)) {
            return "验证失败，没有传入token";
        } else {
            LOGGER.info("token:" + header);
        }

        // 执行方法
        Object result = pjp.proceed();

        // 打印返回结果
        LOGGER.info("返回结果:" + method + ":" + result);
        return result;
    }
}
